import os
import re
import sys
import socket
import requests
import k8sclient
import threading
from flask import request, Response, jsonify, redirect, url_for
from flask import Flask, send_file, abort, render_template
from datetime import datetime

app = Flask(__name__)

@app.route('/api/unidsas/extract', methods=['POST'])
def unidsas_extract():
  request_data = request.get_json()
  start = request_data.get('start')
  end = request_data.get('end')
  ipflt = request_data.get('ipflt')
  portflt = request_data.get('portflt')
  entityflt = request_data.get('entityflt')
  appflt = request_data.get('appflt')
  k8sclient.create_extract(start, end, ipflt, portflt, entityflt, appflt)

  return jsonify({"code": "200", "msg": "操作成功", "success": True})

@app.route('/api/unidsas/extractFileList', methods=['GET'])
def unidsas_extract_file_list():
  directory = '/uniextract'
  files = []

  try:
    for filename in os.listdir(directory):
      filepath = os.path.join(directory, filename)
      if os.path.isfile(filepath):
        file_info = {
          'name': filename,
          'size': os.path.getsize(filepath),
          'mtime': os.path.getmtime(filepath)
        }
        files.append(file_info)
  except FileNotFoundError:
    return jsonify({"code": "404", "msg": "目录未找到", "success": False}), 404
  except Exception as e:
    return jsonify({"code": "500", "msg": str(e), "success": False}), 500

  return render_template('file_list.html', files=files)

@app.route('/api/unidsas/download/<filename>', methods=['GET'])
def download_file(filename):
  directory = '/uniextract'
  filepath = os.path.join(directory, filename)
  try:
    if os.path.exists(filepath) and os.path.isfile(filepath):
      return send_file(filepath, as_attachment=True)
    else:
      abort(404)
  except Exception as e:
    abort(500, description=str(e))

@app.template_filter('datetimeformat')
def datetimeformat(value):
  return datetime.fromtimestamp(value).strftime('%Y-%m-%d %H:%M:%S')

@app.route('/api/unidsas/extractJobList', methods=['GET'])
def unidsas_extract_job_list():
  jobs = k8sclient.list_extract()
  sorted_jobs = sorted(jobs, key=lambda job: job['start_time'], reverse=True)
  return render_template('extract_list.html', jobs=sorted_jobs)


if __name__ == '__main__':
  port = int(sys.argv[1])
  app.run(host='0.0.0.0', port=port)
